<?php

namespace MainBundle\EventListener;

use Doctrine\Common\Persistence\Event\LifecycleEventArgs;
use Doctrine\ORM\Event\PreUpdateEventArgs;
use Symfony\Bridge\Monolog\Logger;
use Symfony\Component\DependencyInjection\ContainerInterface;
use Symfony\Component\Security\Core\Authentication\Token\Storage\TokenStorage;
use Symfony\Component\Security\Core\User\UserInterface;
use Symfony\Component\Translation\IdentityTranslator;

class EntityListener
{
    /** @var ContainerInterface */
    protected $container;
    /** @var TokenStorage */
    protected $tokenStorage;
    /** @var object|Logger */
    protected $logger;
    /** @var object|IdentityTranslator */
    protected $translator;
    /** @var object|UserInterface|null  */
    protected $user;

    /**
     * EntityListener constructor.
     * @param ContainerInterface $container
     * @param TokenStorage $tokenStorage
     */
    public function __construct(ContainerInterface $container, TokenStorage $tokenStorage)
    {
        $this->container = $container;
        $this->tokenStorage = $tokenStorage;
        $this->logger = $container->get('logger');
        $this->translator = $container->get('translator');

        if ($token = $tokenStorage->getToken()) {
            $this->user = $token->getUser();
        } else $this->user = null;
    }

    protected function set($entity, $property, $value)
    {
        $em = $this->container->get('doctrine.orm.entity_manager');
        $qb = $em->createQueryBuilder();
        $qb->update(get_class($entity), 'entity')
            ->set("entity.$property", ":value")
            ->setParameter('value', $value)
            ->where("entity = :entity")
            ->setParameter('entity', $entity)
            ->getQuery()
            ->execute();
    }

    /**
     * @param PreUpdateEventArgs $args
     * @throws \Exception
     */
    public function preUpdate(PreUpdateEventArgs $args) {}

    /**
     * @param LifecycleEventArgs $args
     * @throws \Exception
     */
    public function prePersist(LifecycleEventArgs $args) {}

    /**
     * @param LifecycleEventArgs $args
     * @throws \Exception
     */
    public function postPersist(LifecycleEventArgs $args) {}

    /**
     * @param LifecycleEventArgs $args
     * @throws \Exception
     */
    public function postUpdate(LifecycleEventArgs $args) {}

    /**
     * @param LifecycleEventArgs $args
     * @throws \Exception
     */
    public function preRemove(LifecycleEventArgs $args) {}

    /**
     * @param LifecycleEventArgs $args
     * @throws \Exception
     */
    public function postRemove(LifecycleEventArgs $args) {}
}
